<template>
  <div>
    <div class="page-title">会员管理</div>
    
    <div class="card-container">
      <div class="search-form">
        <el-form :inline="true" :model="searchForm">
          <el-form-item label="会员姓名">
            <el-input v-model="searchForm.name" placeholder="请输入会员姓名" />
          </el-form-item>
          <el-form-item label="手机号">
            <el-input v-model="searchForm.phone" placeholder="请输入手机号" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      
      <div class="table-operations">
        <el-button type="primary" @click="handleAdd">
          <el-icon><Plus /></el-icon>
          新增会员
        </el-button>
      </div>
      
      <el-table :data="tableData" border style="width: 100%">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="姓名" width="120" />
        <el-table-column prop="phone" label="手机号" width="160" />
        <el-table-column prop="password" label="密码" width="160" />
        <el-table-column prop="points" label="积分" width="120" />
        <el-table-column prop="memberLevel" label="会员等级" width="160">
          <template #default="{ row }">
            {{ getLevelText(row.memberLevel) }}
          </template>
        </el-table-column>
        <el-table-column prop="balance" label="余额(元)" width="160">
          <template #default="{ row }">
            ¥{{ row.balance }}
          </template>
        </el-table-column>
        <!-- 状态 -->
        <el-table-column prop="status" label="状态" width="120">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'danger'">
              {{ row.status === 1 ? '启用' : '停用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="注册时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" text @click="handleEdit(row)">编辑</el-button>
            <el-button type="primary" text @click="handleAddBalance(row)">添加余额</el-button>
            <!-- <el-button type="danger" text @click="handleDelete(row)">删除</el-button> -->
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.pageSize"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    
    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增会员' : '编辑会员'"
      width="500px"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="formRules"
        label-width="100px"
      >
        <el-form-item label="姓名" prop="name">
          <el-input v-model="form.name" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="密码" prop="password" >
          <el-input 
            v-model="form.password" 
            placeholder="请输入密码"
            type="password"
            show-password
          />
        </el-form-item>
        <el-form-item label="会员等级" prop="memberLevel">
          <el-select v-model="form.memberLevel" placeholder="请选择等级" style="width: 100%">
            <el-option label="普通会员" value="regular" />
            <el-option label="银卡会员" value="silver" />
            <el-option label="金卡会员" value="gold" />
            <el-option label="白金会员" value="platinum" />
          </el-select>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
          确定
        </el-button>
      </template>
    </el-dialog>

    <!-- 添加余额对话框 -->
    <el-dialog
      v-model="balanceDialogVisible"
      title="添加余额"
      width="400px"
      @close="handleBalanceDialogClose"
    >
      <el-form
        ref="balanceFormRef"
        :model="balanceForm"
        :rules="balanceFormRules"
        label-width="100px"
      >
        <el-form-item label="当前余额">
          <span style="color: #f56c6c; font-weight: bold;">¥{{ currentMember?.balance || 0 }}</span>
        </el-form-item>
        <el-form-item label="充值金额" prop="amount">
          <el-input-number
            v-model="balanceForm.amount"
            :min="100"
            :max="10000"
            :precision="2"
            :step="100"
            style="width: 100%"
            placeholder="请输入充值金额"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="balanceDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleBalanceSubmit" :loading="balanceSubmitLoading">
            确认充值
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import type { Member } from '@/types'
import { getMembers, createMember, updateMember, deleteMember, addBalance } from '@/api/members'

const searchForm = reactive({
  name: '',
  phone: '',
  level: ''
})

const tableData = ref<Member[]>([])
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0
})

const dialogVisible = ref(false)
const dialogType = ref<'add' | 'edit'>('add')
const submitLoading = ref(false)
const formRef = ref<FormInstance>()

// 添加余额相关
const balanceDialogVisible = ref(false)
const balanceFormRef = ref<FormInstance>()
const balanceSubmitLoading = ref(false)
const currentMember = ref<Member | null>(null)
const balanceForm = reactive({
  amount: 0,
  remark: ''
})

const form = reactive<Partial<Member>>({
  name: '',
  phone: '',
  password: '',
  email: '',
  birthday: '',
  memberLevel: 'regular'
})

const formRules: FormRules = {
  name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度至少为6位', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ]
}

// 余额表单验证规则
const balanceFormRules: FormRules = {
  amount: [
    { required: true, message: '请输入充值金额', trigger: 'blur' },
    { type: 'number', min: 0.01, message: '充值金额必须大于0', trigger: 'blur' }
  ],
  remark: [
    { max: 200, message: '备注长度不超过200个字符', trigger: 'blur' }
  ]
}

const loadData = async () => {
  try {
    const params = {
      ...searchForm,
      current: pagination.current,
      size: pagination.pageSize
    }
    const { records, total } = await getMembers(params)
    tableData.value = records
    pagination.total = total
  } catch (error) {
    console.error('加载数据失败:', error)
  }
}

const handleSearch = () => {
  pagination.current = 1
  loadData()
}

const handleReset = () => {
  searchForm.name = ''
  searchForm.phone = ''
  searchForm.level = ''
  handleSearch()
}

const handleSizeChange = (val: number) => {
  pagination.pageSize = val
  loadData()
}

const handleCurrentChange = (val: number) => {
  pagination.current = val
  loadData()
}

const handleAdd = () => {
  dialogType.value = 'add'
  Object.assign(form, {
    name: '',
    phone: '',
    password: '',
    email: '',
    birthday: '',
    memberLevel: 'regular'
  })
  dialogVisible.value = true
}

const handleEdit = (row: Member) => {
  dialogType.value = 'edit'
  // 编辑时不包含密码字段
  // const { password, ...memberWithoutPassword } = row
  Object.assign(form, row)
  dialogVisible.value = true
}

// 处理添加余额
const handleAddBalance = (row: Member) => {
  currentMember.value = row
  balanceForm.amount = 0
  balanceForm.remark = ''
  balanceDialogVisible.value = true
}

// 提交余额充值
const handleBalanceSubmit = async () => {
  if (!balanceFormRef.value || !currentMember.value) return
  
  await balanceFormRef.value.validate(async (valid) => {
    if (valid) {
      balanceSubmitLoading.value = true
      try {
        await addBalance({
          id: currentMember.value.id,
          balance: balanceForm.amount
        })
        ElMessage.success(`成功为 ${currentMember.value.name} 充值 ¥${balanceForm.amount}`)
        balanceDialogVisible.value = false
        loadData() // 刷新数据
      } catch (error) {
        console.error('充值失败:', error)
        ElMessage.error('充值失败')
      } finally {
        balanceSubmitLoading.value = false
      }
    }
  })
}

// 关闭余额对话框
const handleBalanceDialogClose = () => {
  balanceFormRef.value?.resetFields()
  currentMember.value = null
}


const handleDelete = async (row: Member) => {
  try {
    await ElMessageBox.confirm('确定要删除该会员吗？', '提示', {
      type: 'warning'
    })
    await deleteMember(row.id)
    ElMessage.success('删除成功')
    loadData()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
    }
  }
}

const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      submitLoading.value = true
      try {
        if (dialogType.value === 'add') {
          // 新增会员时包含密码
          await createMember(form)
          ElMessage.success('添加成功')
        } else {
          // 编辑会员时排除密码字段，避免提交空密码
          // const { password, ...updateData } = form
          await updateMember(form)
          ElMessage.success('更新成功')
        }
        dialogVisible.value = false
        loadData()
      } catch (error) {
        console.error('提交失败:', error)
      } finally {
        submitLoading.value = false
      }
    }
  })
}

const getLevelType = (level: string) => {
  const map: Record<string, string> = {
    regular: '',
    silver: 'info',
    gold: 'warning',
    platinum: 'danger'
  }
  return map[level] || ''
}

const getLevelText = (level: string) => {
  const map: Record<string, string> = {
    regular: '普通会员',
    silver: '银卡会员',
    gold: '金卡会员',
    platinum: '白金会员'
  }
  return map[level] || level
}

const formatDate = (date: string) => {
  return new Date(date).toLocaleString()
}

onMounted(() => {
  loadData()
})
</script>